import React, { Component } from 'react';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Divider,
  Drawer,
  Form,
  Input,
  Popconfirm,
  Radio,
  Row,
  Select,
  Tabs,
  Tree,
  Upload,
} from 'antd';
import styled from 'styled-components';
import BaseComponent from '@/components/BaseComponent';
import iconAgreement from '@/assets/icon_agreement.png';
import { defDrawerWidth, bmxyImgPrefixUrl, njzdImgPrefixUrl } from '@/defaultSettings';
import { DivFooter, LFlexHDiv } from '@/components/MHtmlTag';

import {
  FormItem4Input,
  FormItem4Select,
  FormItem4Radio,
  FormItem5Select,
  FormItem4TreeSelect,
  FormItem4InputPwd,
} from '../MCols';
import styles from './index.less';

const { TabPane } = Tabs;
const ThumbnailBox = styled.div`
  width: 103px;
  height: 103px;
  display: flex;
  align-items: center;
  margin-top: 8px;

  .thumbnailImage {
    width: 103px;
    height: 103px;
  }

  .delBtn {
    margin-left: 16px;
  }
`;

/**
 * 编辑页面
 */
@Form.create()
class AddOrEditViewPlus extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: '1',
      ndaUrl: '',
      ndaPath: '',
      // 是否正在上传
      isUploading: false,
      xbData: [
        {
          dictName: '男',
          dictValue: 1,
        },
        {
          dictName: '女',
          dictValue: 2,
        },
      ],
      statusData: [
        {
          dictName: '正常',
          dictValue: 1,
        },
        {
          dictName: '禁用',
          dictValue: 0,
        },
      ],
      record: {},
    };
  }

  componentDidMount() {
    const { record, isAddOrEdit } = this.props;
    this.setState({
      record,
      ndaUrl: record.ndaUrl,
    });
    // // 新增时,用户状态默认设置为1:启用
    // if (isAddOrEdit) {
    //   const { form } = this.props;
    //   debugger;
    //   form.setFieldsValue({ status: 1 });
    // }
  }

  render() {
    let { onClose, record, form, roleData, orgData, visible, isAddOrEdit, title } = this.props;
    if (isAddOrEdit == true) {
      record = {};
    }
    // 从state中获取参数
    const { activeKey, ...otherProps } = this.state;
    const disabled = false;
    return (
      <Drawer
        title={title}
        placement="right"
        width={defDrawerWidth}
        closable
        onClose={e => {
          if (onClose) {
            onClose(e);
          }
        }}
        visible={visible}
        className={styles.editableTable}
      >
        <Tabs defaultActiveKey={activeKey} onChange={this.handleTabChange}>
          <TabPane tab="基本信息" key="1" />
          <TabPane tab="账号信息" key="2" />
        </Tabs>

        <Card bordered>
          {/* 基本信息 */}
          <Row gutter={16} style={{ display: activeKey == 1 ? 'block' : 'none' }}>
            <FormItem4TreeSelect
              form={form}
              label="机构名称"
              fieldName="orgId"
              required
              items={orgData}
              initialValue={record ? record.orgId : ''}
            />
            <FormItem4Input
              form={form}
              label="所属部门"
              fieldName="departmentName"
              required={false}
              initialValue={record ? record.departmentName : ''}
            />
            <FormItem4Input
              form={form}
              label="专业"
              fieldName="profession"
              required={false}
              initialValue={record ? record.profession : ''}
            />
            <FormItem4Input
              form={form}
              label="职务"
              fieldName="job"
              required={false}
              initialValue={record ? record.job : ''}
            />
            <FormItem4Input
              form={form}
              label="职称"
              fieldName="jobTitle"
              required={false}
              initialValue={record ? record.jobTitle : ''}
            />
            <FormItem4Input
              form={form}
              label="姓名"
              fieldName="nickname"
              required
              initialValue={record ? record.nickname : ''}
            />
            <FormItem4Select
              form={form}
              label="性别"
              fieldName="gender"
              required={false}
              items={this.state.xbData}
              initialValue={record ? record.gender : ''}
            />
            <FormItem4Input
              form={form}
              label="联系电话"
              fieldName="mobile"
              required
              initialValue={record ? record.mobile : ''}
            />
            <FormItem4Input
              form={form}
              label="邮箱"
              fieldName="email"
              required={false}
              initialValue={record ? record.email : ''}
            />
            <FormItem4Input
              form={form}
              label="邮政编码"
              fieldName="postalCode"
              required={false}
              initialValue={record ? record.postalCode : ''}
            />
            <FormItem4Input
              form={form}
              label="邮寄地址"
              fieldName="postalAddress"
              required={false}
              initialValue={record ? record.postalAddress : ''}
            />
          </Row>
          <Row style={{ display: activeKey == 1 ? 'block' : 'none', marginBottom: '16px' }}>
            <Col className="gutter-row" span={12}>
              <Form.Item label="保密协议" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
                {this.state.ndaUrl && this.state.ndaUrl != '' ? (
                  <div className={styles.agreementImageBox}>
                    <img
                      src={iconAgreement}
                      className={styles.agreementImage}
                      onClick={() => {
                        const url = `${bmxyImgPrefixUrl}${this.state.ndaUrl}`;
                        window.open(url);
                      }}
                    />
                  </div>
                ) : (
                  <Upload
                    listType="picture-card"
                    className={styles.agreementImage}
                    showUploadList={false}
                    action="/api/file/file/uploadFile4Report"
                    beforeUpload={this.handleUploadBefore}
                    onChange={info => {
                      this.handleUploadChange({ info });
                    }}
                  >
                    上传
                  </Upload>
                )}
                {this.state.ndaUrl && this.state.ndaUrl != '' ? (
                  <div>
                    {disabled ? null : (
                      <>
                        <Button
                          type="primary"
                          size="small"
                          style={{ marginTop: '6px' }}
                          className={styles.previewBtn}
                          onClick={() => {
                            window.open(`${bmxyImgPrefixUrl}${this.state.ndaUrl}`);
                          }}
                        >
                          预览
                        </Button>
                        <Popconfirm
                          title="确定删除吗?"
                          onConfirm={() => {
                            if (this.handleDelImage) {
                              this.handleDelImage();
                            }
                          }}
                        >
                          <Button type="danger" size="small" style={{ marginLeft: '4px' }}>
                            删除
                          </Button>
                        </Popconfirm>
                      </>
                    )}
                  </div>
                ) : (
                  <div />
                )}
              </Form.Item>
            </Col>
          </Row>
          {/* 账号信息 */}
          <Row gutter={16} style={{ display: activeKey == 2 ? 'block' : 'none' }}>
            <FormItem4Input
              form={form}
              label="登陆账号"
              fieldName="username"
              required
              initialValue={record ? record.username : ''}
            />
            {/* <FormItem4InputPwd
             form={form}
             label={'登录密码'}
             fieldName={'password'}
             required={true}
             initialValue={record ? record['password'] : ''}
             ></FormItem4InputPwd> */}
            <FormItem5Select
              form={form}
              label="请选择权限"
              fieldName="roleId"
              required
              items={roleData}
              initialValue={record ? record.roleId : ''}
            />
            <FormItem4Radio
              form={form}
              label="状态"
              fieldName="status"
              required
              items={this.state.statusData}
              // initialValue={isAddOrEdit ? 1 : record ? record['status'] : ''}
              initialValue={record ? record.status : ''}
            />
          </Row>
        </Card>

        <DivFooter>
          <LFlexHDiv flex="1" justifyContent="center">
            <Button
              style={{
                marginRight: 8,
                width: '120px',
              }}
              onClick={() => {
                if (onClose) {
                  onClose();
                }
              }}
            // loading={this.props.isPosting}
            >
              取消
            </Button>

            <Button
              style={{
                marginRight: 8,
                width: '120px',
              }}
              onClick={this.handleSave}
            >
              暂存
            </Button>

            <Popconfirm
              title="确认执行当前操作吗?"
              onConfirm={this.handleSubmit}
              okText="是"
              cancelText="否"
            >
              <Button
                style={{
                  marginRight: 8,
                  width: '120px',
                }}
                type="primary"
              // loading={this.props.isPosting}
              >
                提交
              </Button>
            </Popconfirm>
          </LFlexHDiv>
        </DivFooter>
      </Drawer>
    );
  }

  /**
   * 执行暂存
   */
  handleSave = () => {
    const { form, onSave, record } = this.props;
    form.validateFields((err, values) => {
      if (err) {
        // 表单校验失败，有必填项未填写完整
        this.errorMessage('必填项未填写完整');
        return;
      }
      // 表单校验通过，可以继续处理提交逻辑
        // 表单数据
      const fieldsValue = form.getFieldsValue();
      if (onSave) {
        fieldsValue.id = record.id;
        onSave(fieldsValue);
      }
    });
 

    /* form.validateFields((err, fieldsValue) => {
     if (err) return;
     // form.resetFields();
     if (onSave) {
     fieldsValue['id'] = record.id;
     onSave(fieldsValue);
     }
     }); */
  };

  /**
   * 执行提交
   */
  handleSubmit = () => {
    const { form, onSubmit, record } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err){
        // 表单校验失败，有必填项未填写完整
        this.errorMessage('必填项未填写完整');
        return;
      } 
      const fieldsValueObj = form.getFieldsValue();
      if (onSubmit) {
        fieldsValueObj.id = record.id;
        onSubmit(fieldsValueObj);
      }
    });
  };

  handleDelImage = () => {
    this.setState({
      ndaUrl: '',
      ndaPath: '',
    });
  };

  handleUploadBefore = (file, fileList) => {
    this.setState({ isUploading: true }, () => {
      this.hide = this.loadingMessage('正在上传...');
    });
    return true;
  };

  handleUploadChange = ({ info }) => {
    if (info.file.status !== 'uploading') {
      this.setState(
        {
          fileList: info.fileList,
        },
        () => { }
      );
    }
    if (info.file.status === 'done') {
      const {response} = info.file;
      const {
        data: { filePath, originalFilename },
      } = response;
      const arr = filePath.split('/');
      // 文件前缀
      const prefix = arr[arr.length - 2];
      const url = `${prefix}/${originalFilename}`;
      this.setState({
        ndaUrl: url,
        ndaPath: filePath,
        isUploading: false,
      });
      if (this.hide) {
        this.hide();
      }
      this.successMessage('上传成功');
    } else if (info.file.status === 'error') {
      this.errorMessage('文件上传出错,请联系管理员');
    }
  };

  handleTabChange = key => {
    this.setState({ activeKey: key });
  };
}

export default AddOrEditViewPlus;
